package com.g7.figmaapi.common.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Random;

/**
 * @author: taoxiangqian
 * @explain: PKCE工具类
 * @since: 2023/10/26 14:35
 */
public class PKCEGeneratorUtils {
    private static final int CODE_VERIFIER_LENGTH = 64;
    private static final int CODE_CHALLENGE_LENGTH = 43;

    /**
     * 生成code verifier
     *
     * @return java.lang.String
     * @author taoxiangqian
     * @since 2023/10/26
     **/
    public static String generateCodeVerifier() {
        SecureRandom secureRandom = new SecureRandom();
        byte[] codeVerifierBytes = new byte[32];
        secureRandom.nextBytes(codeVerifierBytes);
        return Base64.getUrlEncoder().withoutPadding().encodeToString(codeVerifierBytes);
    }

    /**
     * 生成 code challenge
     *
     * @param codeVerifier 随机生成的校验码
     * @return java.lang.String
     * @author taoxiangqian
     * @since 2023/10/26
     **/
    public static String generateCodeChallenge(String codeVerifier) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] codeVerifierBytes = codeVerifier.getBytes();
        byte[] codeChallengeBytes = messageDigest.digest(codeVerifierBytes);
        return Base64.getUrlEncoder().withoutPadding().encodeToString(codeChallengeBytes);
    }
}
